import { defineStore } from 'pinia';
import { Category } from '../../types';
import StorageManager from '../../utils/storage';
import { nanoid } from '@/utils/nanoid-polyfill';

interface CategoryState {
  categories: Category[];
  loading: boolean;
  error: string | null;
}

export const useCategoryStore = defineStore('category', {
  state: (): CategoryState => ({
    categories: [],
    loading: false,
    error: null
  }),

  getters: {
    // 获取所有分类
    getAllCategories: (state) => state.categories,
    
    // 按类型获取分类
    getCategoriesByType: (state) => (type: 'contact' | 'gift') => {
      return state.categories.filter(category => category.type === type);
    },
    
    // 获取分类详情
    getCategoryById: (state) => (id: string) => {
      return state.categories.find(category => category.id === id);
    }
  },

  actions: {
    // 加载分类列表
    async loadCategories() {
      this.loading = true;
      this.error = null;
      try {
        this.categories = await StorageManager.getCategories();
      } catch (error) {
        this.error = '加载分类失败';
        console.error('加载分类失败:', error);
      } finally {
        this.loading = false;
      }
    },

    // 添加分类
    async addCategory(category: Omit<Category, 'id' | 'createTime' | 'updateTime'>) {
      this.loading = true;
      this.error = null;
      try {
        const newCategory: Category = {
          ...category,
          id: nanoid(),
          createTime: new Date().toISOString(),
          updateTime: new Date().toISOString()
        };
        await StorageManager.saveCategory(newCategory);
        this.categories.push(newCategory);
        return newCategory.id;
      } catch (error) {
        this.error = '添加分类失败';
        console.error('添加分类失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 更新分类
    async updateCategory(category: Category) {
      this.loading = true;
      this.error = null;
      try {
        const updatedCategory = {
          ...category,
          updateTime: new Date().toISOString()
        };
        await StorageManager.saveCategory(updatedCategory);
        const index = this.categories.findIndex(c => c.id === category.id);
        if (index > -1) {
          this.categories[index] = updatedCategory;
        }
      } catch (error) {
        this.error = '更新分类失败';
        console.error('更新分类失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 删除分类
    async deleteCategory(id: string) {
      this.loading = true;
      this.error = null;
      try {
        await StorageManager.deleteCategory(id);
        this.categories = this.categories.filter(category => category.id !== id);
      } catch (error) {
        this.error = '删除分类失败';
        console.error('删除分类失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    },

    // 清空分类列表
    async clearCategories() {
      this.loading = true;
      this.error = null;
      try {
        for (const category of this.categories) {
          await StorageManager.deleteCategory(category.id);
        }
        this.categories = [];
      } catch (error) {
        this.error = '清空分类失败';
        console.error('清空分类失败:', error);
        throw error;
      } finally {
        this.loading = false;
      }
    }
  },

  persist: true
}); 